package com.gitee.mocoffee.log.spring;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.MDC;

import com.gitee.mocoffee.misc.IdGenKit;

import jodd.util.StringUtil;

public class LogTraceAspect {
    private static final String LOG_TRACEID = "TRACEID";

    @Retention(RUNTIME)
    @Target({METHOD})
    public @interface Trace {
        String value() default "";
    }

    public Object addTrace(ProceedingJoinPoint pjp, Trace trace) throws Throwable {
        String traceValue = trace.value();

        if (StringUtil.isBlank(traceValue)) {
            traceValue = IdGenKit.generate();
        }

        MDC.put(LOG_TRACEID, traceValue);
        try {
            return pjp.proceed();
        } finally {
            MDC.remove(LOG_TRACEID);
        }
    }
}
